package com.ease.web.struts2;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.apache.struts2.ServletActionContext;

import freemarker.template.SimpleHash;
import freemarker.template.Template;
import freemarker.template.TemplateModel;

/**
 * 
 * @author nathanleewei
 * 
 */
public class FreeMarkerResult extends org.apache.struts2.views.freemarker.FreemarkerResult {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3817226245605360485L;

	// private static final Log log = LogFactory.getLog(FreemarkerResult.class);

	public static final String KEY_WEBWORK_TAG_LIB = "ww";

	public static final String KEY_BASE = "base";

	protected Writer getWriter() throws IOException {
		return new OutputStreamWriter(ServletActionContext.getResponse().getOutputStream(), ServletActionContext.getResponse().getCharacterEncoding());
	}

	protected boolean preTemplateProcess(Template template, TemplateModel model) throws IOException {
		super.preTemplateProcess(template, model);
		inject(model);

		return true;
	}

	private void inject(TemplateModel model) {
		SimpleHash hash = (SimpleHash) model;

		// try {
		// TaglibFactory factory = (TaglibFactory)
		// hash.get(FreemarkerManager.KEY_JSP_TAGLIBS);
		// hash.put(KEY_WEBWORK_TAG_LIB, factory.get("/WEB-INF/webwork.tld"));

		hash.put(KEY_BASE, ServletActionContext.getRequest().getContextPath());
		// } catch (TemplateModelException e) { log.error("inject model error:
		// ", e); }

	}
}
